#!/usr/bin/env python
# -*- coding: utf-8 -*- #   
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api.urlfetch import *
from google.appengine.api import users
from google.appengine.api import xmpp
from google.appengine.ext import webapp
import datetime
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class IntVar(db.Model):
	Num_Received=db.IntegerProperty()
class Messages(db.Model):
	Time=db.DateTimeProperty(auto_now_add=True)
	Content=db.StringProperty()
	To=db.StringProperty()
	Sender=db.StringProperty()
class XMPPHandler2(webapp.RequestHandler):
	def get(self):
		user=users.get_current_user()
		xmpp.send_message(user.email(),self.request.get("content"))
		self.response.out.write( "send successfully")
		self.response.out.write('<a href="/talk">talk</a>')
class XMPPHandler(webapp.RequestHandler):
	def post(self):
		intvar=IntVar.all()
		if intvar.count()==0 :
			intvar1=IntVar()
			intvar1.Num_Received=1
			intvar1.put()
		else:
			for intvar1 in intvar:
				intvar1.Num_Received=intvar1.Num_Received+1
				intvar1.put()

		message = xmpp.Message(self.request.POST)
		mes=Messages()
		mes.Content=message.body
		mes.Sender=message.sender
		mes.To=message.to
		mes.put()
		if message.body[0:5].lower() == 'hello':
			message.reply("Greetings!")
		elif message.body.lower().find('name')!=-1:
			message.reply("My name is IcyBot!")	
		else:
			message.reply("It's recorded!")
    		
class MainHandler(webapp.RequestHandler):
	def get(self):
		self.response.out.write("IcyBot ibot42 is Online! <br>It will help you communicate with your other device(such as Android) through gtalk<br>Add ibot42@appspot.com in gtalk and talk to it to get recorded<br>Click the Chrome Extension Link below to download the chrome extension and access it easier<br>you can view the logs here")
		user=users.get_current_user()
		if users.get_current_user():
			self.response.out.write( "<br>Welcome, %s"%user.email())
			self.response.out.write('<a href="%s">log out</a>'%users.create_logout_url(self.request.uri))
			self.response.out.write('<br><a href="/talk">talk to me</a>')
			self.response.out.write('<br><a href="/log">logs</a>')
			
		else:
			self.response.out.write('<br><a href="%s">log in</a>'%users.create_login_url(self.request.uri))
		self.response.out.write('<br><a href="/talktome.crx">Chrome Extension</a>')
		self.response.out.write('<br>Any problem, contact me via : wsmlby@gmail.com')
	
		
		
class Logs(webapp.RequestHandler):
	def get(self):
		user=users.get_current_user()
		if users.get_current_user():
			self.response.out.write( "Welcome, %s"%user.email())
			self.response.out.write('<a href="%s">log out</a><br>'%users.create_logout_url(self.request.uri))
		else:
			self.redirect(users.create_login_url(self.request.uri))
			return
		megs=Messages.all()
		for meg in megs:
			x=meg.Sender.__str__()
			if x.find(user.email().__str__())!=-1:
				self.response.out.write(u"%s<br>"%meg.Content)
class talk(webapp.RequestHandler):
	def get(self):
		user=users.get_current_user()
		if users.get_current_user():
			self.response.out.write( "Welcome, %s"%user.email())
			self.response.out.write('<a href="%s">log out</a><br>'%users.create_logout_url(self.request.uri))
		else:
			self.redirect(users.create_login_url(self.request.uri))
			return
		user=users.get_current_user()
		self.response.out.write('<form action="/send">')
		self.response.out.write('<div>what?<input type="text" name="content"></div><div><input type="submit" value="send"></div>')
		megs=Messages.all()
		time=db.DateTimeProperty(auto_now_add=True)
		for meg in megs:
			if meg.Time.date()==datetime.date.today():
				x=meg.Sender.__str__()
				if x.find(user.email().__str__())!=-1:
					self.response.out.write(u"<br>%s"%meg.Content)
def main():
    application = webapp.WSGIApplication([('/send',XMPPHandler2),('/log',Logs),('/talk',talk),('/',MainHandler),('/_ah/xmpp/message/chat/', XMPPHandler)],
                                     debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
